import { CALL_API } from 'redux-api-middleware'
import { extend } from 'lodash/fp'
import cookie from 'react-cookie'
import config from 'config'

// Constants
export const FILEUPLOAD_REQUEST = 'FILEUPLOAD_REQUEST'
export const FILEUPLOAD_SUCCESS = 'FILEUPLOAD_SUCCESS'
export const FILEUPLOAD_FAILURE = 'FILEUPLOAD_FAILURE'

export const UPUSERHEAD_REQUEST = 'UPUSERHEAD_REQUEST'
export const UPUSERHEAD_SUCCESS = 'UPUSERHEAD_SUCCESS'
export const UPUSERHEAD_FAILURE = 'UPUSERHEAD_FAILURE'

// 上传文件
export function fileUpload (fromData) {
  return {
    [CALL_API]: {
      endpoint: config.api_root_v1 + '/files.php?c=files&a=uploadImg',
      method: 'POST',
      body: fromData,
      types: [
        FILEUPLOAD_REQUEST,
        {
          type: FILEUPLOAD_SUCCESS,
          payload: (action, state, res) => {
            return res.json()
          }
        },
        FILEUPLOAD_FAILURE
      ]
    }
  }
}

// 修改头像
export function upuserHead (uid, headimg) {
  return {
    [CALL_API]: {
      endpoint: config.api_root_v1 + '/user.php?c=user',
      method: 'POST',
      body: JSON.stringify({
        jsonrpc: '2.0',
        method: 'upuserHead',
        params: [{
          "u_id": uid,
          "u_headimg": headimg
        }],
        id: 1
      }),
      credentials: "include",
      types: [
        UPUSERHEAD_REQUEST,
        {
          type: UPUSERHEAD_SUCCESS,
          payload: (action, state, res) => {
            return res.json()
          }
        },
        {
          type: UPUSERHEAD_FAILURE,
          payload: (action, state, res) => {
            return res.json()
          }
        }
      ]
    }
  }
}

export const actions = {
  fileUpload,
  upuserHead
}

// Action Handlers
const ACTION_HANDLERS = {
  [UPUSERHEAD_REQUEST]: (state, action) => {
    return ({ ...state, userhead: { isFetching: true, error: {}, header: {} } })
  },
  [UPUSERHEAD_SUCCESS]: (state, action) => {
    return ({ ...state, userhead: { isFetching: true, error: {}, header: action.payload } })
  },
  [UPUSERHEAD_FAILURE]: (state, action) => {
    return ({ ...state, userhead: { isFetching: true, error: action.payload, header: {} } })
  },
  [FILEUPLOAD_REQUEST]: (state, action) => {
    return ({ ...state, fileUpload: { isFetching: true, error: {}, upload: {} } })
  },
  [FILEUPLOAD_SUCCESS]: (state, action) => {
    return ({ ...state, fileUpload: { isFetching: false, error: {}, upload: action.payload } })
  },
  [FILEUPLOAD_FAILURE]: (state, action) => {
    return ({ ...state, fileUpload: { isFetching: false, error: {}, upload: {} } })
  }
}

// Reducers
const initialState = { fileUpload: { isFetching: false, error: {}, upload: {} }, userhead: { isFetching: true, error: {}, header: {} } }
export default function spaceReducer (state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]
  return handler ? handler(state, action) : state
}
